<script setup lang="ts">
import type { FormInstance, FormRules } from 'element-plus'
import { Lock, PictureRounded, User } from '@element-plus/icons-vue'
import { computed, onMounted, reactive, ref, watch } from 'vue'
import { useRouter } from 'vue-router'
import { login } from '~/api/modules/sysUser'
import { setToken } from '~/composables/auth'
import { cryptoDecrypt } from '~/composables/crypto'
import { useCachedUsers } from './composable'

defineOptions({ name: 'Login' })

const formRef = ref<FormInstance>()
const info = reactive({
  loginName: '',
  password: '',
  code: '',
  rememberMe: true,
})
const submitting = ref(false)
const rules: FormRules = {
  loginName: [
    { required: true, message: '请输入用户名' },
  ],
  password: [
    { required: true, message: '请输入密码' },
  ],
  // code: [
  //   { required: true, message: '请输入验证码' },
  // ],
}
const { users, updateCachedUsers } = useCachedUsers()
const userStore = useUserStore()
const router = useRouter()
const { updateProjectVersion } = useServiceUpdate()
const captcha = ref('')

const logoTitle = computed(() => {
  return APP_TITLE
})

function getCaptcha() {
  captcha.value = `${SERVICE_BASIC}/sysUser/captcha?t=${Date.now()}`
}
async function submitForm() {
  const isValid = await formRef.value?.validate().catch(() => { })
  if (isValid) {
    submitting.value = true
    try {
      const { data } = await login({
        loginName: info.loginName,
        passWord: info.password,
      })
      if (data?.tk) {
        setToken(data.tk)
        userStore.setUserInfo(data)

        // 更新项目hash
        updateProjectVersion()
      }
      if (info.rememberMe) {
        updateCachedUsers(info.loginName, info.password)
      }
      router.replace('/system-navigation')
    }
    catch (e) {
      // getCaptcha()
    }
    finally {
      submitting.value = false
    }
  }
}

watch(
  () => info.loginName,
  (val) => {
    if (users.value.has(val)) {
      info.password = cryptoDecrypt(users.value.get(val))
    }
  },
)

onMounted(() => {
  // getCaptcha()

  const v = users.value.keys()
  const u = v.next().value
  if (u) {
    info.loginName = u
    const p = users.value.get(u)
    p && (info.password = cryptoDecrypt(p))
  }
})
</script>

<template>
  <div class="relative h-full w-full overflow-hidden">
    <img src="./login-bg.webp" alt="bg" class="h-full w-full object-cover">
    <div class="logo-title absolute left-4 top-4 z-1 flex items-center gap-2">
      <img src="/logo.svg" alt="logo" class="h-10 w-10">
      <span class="text-2xl text-[#C0E7FF] font-pmzd">{{ logoTitle }}</span>
    </div>
    <div class="login-form absolute left-3/4 top-1/2 z-1 min-h-80 w-110 flex flex-col rounded-lg px-10 pb-10 pt-20 -translate-x-1/2 -translate-y-1/2">
      <div class="text-center text-2xl font-sans" style="letter-spacing: 0.1em;">
        欢迎登录
      </div>
      <div class="mt-2 flex items-center justify-center">
        <span class="text-sm opacity-40">--</span>
        <span class="mx-2 text-sm opacity-80">welcome to login</span>
        <span class="text-sm opacity-40">--</span>
      </div>
      <el-form ref="formRef" :model="info" :rules="rules" size="large" class="mt-10" @keyup.enter="submitForm">
        <el-form-item prop="loginName">
          <el-input
            v-model="info.loginName"
            placeholder="请输入用户名" :maxlength="30"
            :prefix-icon="User" clearable
            style="--el-border-color: transparent;--el-input-hover-border-color: #2E89FA;--el-input-focus-border-color: #2E89FA;--el-input-bg-color: rgba(0,0,0,0.2);--el-input-icon-color: #dddddd;"
          />
        </el-form-item>
        <el-form-item prop="password">
          <el-input
            v-model="info.password"
            show-password type="password" placeholder="请输入密码"
            style="--el-border-color: transparent;--el-input-hover-border-color: #2E89FA;--el-input-focus-border-color: #2E89FA;--el-input-bg-color: rgba(0,0,0,0.2);--el-input-icon-color: #dddddd;"
            :maxlength="30" :prefix-icon="Lock" clearable
          />
        </el-form-item>
        <el-form-item v-if="false" class="captcha-item" prop="code">
          <el-input
            v-model="info.code"
            placeholder="验证码"
            :prefix-icon="PictureRounded"
          >
            <template #suffix>
              <img
                title="点击刷新"
                :src="captcha"
                alt="code"
                width="120"
                height="38"
                class="border-none object-fill"
                @click="getCaptcha"
              >
            </template>
          </el-input>
        </el-form-item>
        <el-form-item class="!mb-2">
          <el-checkbox v-model="info.rememberMe" class="text-sm">
            记住密码
          </el-checkbox>
        </el-form-item>
        <el-form-item>
          <el-button :loading="submitting" class="submit-button w-full" type="primary" @click="submitForm">
            登录
          </el-button>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<style lang="scss">
.login-form {
  background: rgba(33,87,148,0.7);
  box-shadow: inset 0 0 6px 1px rgba(46,137,250,0.9);
  .el-input__wrapper {
    background-color: var(--el-input-bg-color) !important;
  }
  .text-sm {
    font-size: 0.875rem;
    line-height: 1.25rem;
  }
}
.submit-button {
  background-color: transparent;
  background-image: url('./login-button-bg.png');
  background-repeat: no-repeat;
  background-size: 100% 100%;
  background-position: center center;
  border: none;
  padding: 14px;
  transition: all .3s ease;

  --el-button-size: 50px;
  --el-button-bg-color: transparent;
  --el-button-hover-bg-color: transparent;
  --el-button-active-bg-color: transparent;

  &:hover {
    color: #ccc;
    background-image: url('./login-button-hover-bg.png');
  }
}
</style>
